package com.guang.springmybatis.beanfactory;

import com.guang.springmybatis.scan.LGClassPathMapperScanner;
import com.guang.springmybatis.scan.LGScan;
import com.guang.springmybatis.scan.LGMapper;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.TypeFilter;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * @Description
 * @Author liguang
 * @Date 2022/08/23/21:38
 */
public class LGImportDefinitionRegiesty implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        // 在这里来获取得到这里的扫描信息
        Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(LGScan.class.getName());
        String mapperInterfacePath = (String) annotationAttributes.get("value");
        // 利用spring提供的扫描逻辑
        LGClassPathMapperScanner lgClassPathMapperScanner = new LGClassPathMapperScanner(registry);
        lgClassPathMapperScanner.addIncludeFilter(new TypeFilter() {
            @Override
            public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
                ClassMetadata classMetadata = metadataReader.getClassMetadata();
                return classMetadata.isIndependent()&&classMetadata.isInterface();
            }
        });
        lgClassPathMapperScanner.scan(mapperInterfacePath);
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {
        registerBeanDefinitions(importingClassMetadata, registry);
    }
}
